﻿{%              if GenerateNullableReferenceTypes -%}
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("value")]
private string? ConvertToString(object? value, System.Globalization.CultureInfo cultureInfo)
{%              else -%}
private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo)
{%              endif -%}
{
    if (value == null)
    {
        return null;
    }

    if (value is System.Enum)
    {
        var name = System.Enum.GetName(value.GetType(), value);
        if (name != null)
        {
            var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name);
            if (field != null)
            {
                var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) 
                    as System.Runtime.Serialization.EnumMemberAttribute;
                if (attribute != null)
                {
                    return attribute.Value != null ? attribute.Value : name;
                }
            }

            return System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo));
        }
    }
    else if (value is bool) 
    {
        return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant();
    }
    else if (value is byte[])
    {
        return System.Convert.ToBase64String((byte[]) value);
    }
    else if (value.GetType().IsArray)
    {
        var array = System.Linq.Enumerable.OfType<object>((System.Array) value);
        return string.Join(",", System.Linq.Enumerable.Select(array, o => ConvertToString(o, cultureInfo)));
    }

    var result = System.Convert.ToString(value, cultureInfo);
    return (result is null) ? string.Empty : result;
}
